/**
 * 是否开启移动模式
 */
let moveMode = false;
/**
 * 潜能果总数
 */
let toalCount = 0;
/**
 * 原来的潜能果ID
 */
let orignId = null;
/**
 * 潜能果ID
 */
let fruitId = null;
/**
 * 潜能果位置
 * @type {null}
 * @private
 */
let location_ = null;
let requestUrl = null;

function addHandler() {
    requestUrl = "/potency_fruit/insert";

    let roleId = $("#role_id").combobox("getValue");

    if (roleId) {
        $("#roleId").combobox("setValue", roleId);
    }

    $("#potency_dialog").dialog("open");
}

function editHandler() {
    let rowData = $("#potency_list").datagrid("getSelected");

    if (rowData) {
        requestUrl = "/potency_fruit/updateById";

        $("#id").val(rowData.id);
        $("#roleId").combobox("setValue", rowData.roleId);
        $("#propertyId").combobox("setValue", rowData.propertyId);
        $("#location").numberspinner("setValue", rowData.location);

        $("#potency_dialog").dialog("open");
    } else {
        alertMsg("请选择要修改的记录！", "warning");
    }
}

function deleteHandler() {
    let rowData = $("#potency_list").datagrid("getSelected");

    if (rowData) {
        $.messager.confirm("提示", "是否确认删除？", function (bool) {
            if (bool) {
                ajaxPost("/potency_fruit/deleteById", {
                    id: rowData.id
                }, function (resp) {
                    showMsg(resp.message);

                    $("#potency_list").datagrid("reload");
                }, error);
            }
        });
    } else {
        alertMsg("请选择要删除的记录！", "warning");
    }
}

function viewHandler() {
    let rowData = $("#potency_list").datagrid("getSelected");

    if (rowData) {
        $("#role_list").datalist("reload", {
            callback: function () {
                $("#role_list").datalist("selectRecord", rowData.roleId);
            }
        })

        $("#detail_dialog").dialog("open");
    } else {
        alertMsg("请选择要查看的记录！", "warning");
    }
}

/**
 * 加载潜能果图案类型列表
 * @param type 图案类型
 */
function loadPattern(type) {
    // 查询角色经验
    ajaxGet("/potency_fruit_pattern_category/selectByType", {
        type: type
    }, function (resp) {
        let list = resp.data;

        if (list && list.length) {
            let content = "";


            for (let i = 0; i < list.length; i++) {
                let data = list[i];

                content += "<div class='pattern_box'>";
                content += "<div style='font-size: 20px;'>" + data.name + "</div>";
                content += "<div class='green'>" + data.properyName + "</div>";
                content += "<i class='" + (data.active === 1 ? "active" : "") + "'></i>";
                content += "</div>";
            }

            $("#right-menu").empty().append();
        }
    }, error);
}

/**
 * 渲染潜能果
 */
function fetchFruilt() {
    /*
     * 对角相邻的三个潜能果的中心坐标组成一个等腰三角形，三角形的边长为潜能果的直径
     * 中间的潜能果个数为11（7 ~ 11 ~ 7）
     * 面板的宽度取484，所以潜能果的直径为：d ≤ 484 ÷ 11 = 44
     */
    let radius = 20; // 潜能果的半径
    let maxCount = 11; // 最大潜能果数
    let array = [7, 8, 9, 10, 11, 10, 9, 8, 7]; // 每行潜能果数

    let fruits = "";

    fruits += "<div style='margin-top: 10px;'></div>";

    let counter = 0; // 创建一个计数器
    let image = "/images/blank.png"; // 图片初始路径

    for (let i = 0; i < array.length; i++) {
        let count = array[i];

        // 计算每行潜能果的左边距
        let margin = (maxCount - count) * radius;

        // 追加潜能果
        fruits += "<div style='display:flex;margin-left: " + (margin + 16) + "px;'>";

        for (let j = 0; j < count; j++) {
            let location = ++ counter;

            fruits += "<div class='fruit' id='potency_fruit_" + location + "' location='" + location + "'>";
            fruits += "<img class='fruit_image' src='" + image + "' />";
            fruits += "</div>";
        }

        fruits += "</div>";
    }

    fruits += "</div>";

    $("#potency_fruit").empty().append(fruits);
}

/**
 * 加载潜能果
 */
function loadFruilt() {
    // 查询角色潜能果列表
    let rowData = $("#role_list").datalist("getSelected");

    // 给所有掐能果绑定点击事件
    for (let location = 1; location <= 79; location ++) {
        $("#potency_fruit_" + location).attr({
            "location": location
        }).on("click", function () {
            location_ = location;

            viewFruilt();
        });
    }

    if (rowData != null) {
        let roleId = rowData.id;
        let schemaId = $("#potency_schema").combobox("getValue");

        if (schemaId) {
            ajaxGet("/potency_fruit/selectDetails", {
                schemaId: schemaId,
                roleId: roleId
            }, function (resp) {
                let fruits = resp.data;

                if (fruits) {
                    let total = fruits.length;

                    if (total > 0) {
                        toalCount = total;

                        for (let i = 0; i < total; i++) {
                            let fruit = fruits[i];
                            let fruitId = fruit.id;
                            let location = fruit.location;

                            $("#potency_fruit_" + location).attr({
                                "ref": fruitId,
                                "location": location
                            }).unbind("click").on("click", function () {
                                location_ = location;

                                viewFruilt(fruitId);
                            }).children("img.fruit_image").attr({
                                title: fruit.name,
                                src: fruit.image
                            });
                        }
                    }
                }
            }, error);
        }
    }
}

/**
 * 查看潜能果
 */
function viewFruilt(id) {
    fruitId = id;

    if (moveMode  && orignId != null) { // 开启了移动模式，则下一次点击会触发潜能果位置交换操作
        let targetId = fruitId;

        // 移动潜能果
        console.log("移动潜能果：" + orignId + "=>" + targetId);

        ajaxPost("/potency_fruit/move", {
            "orignId": orignId,
            "targetId": targetId,
            "location": location_
        }, function () {
            moveMode = false;
            orignId = null;

            fetchFruilt();
            loadFruilt();
        }, error);
    } else {
        // 查询角色潜能果详情
        if (fruitId != null) {
            ajaxGet("/potency_fruit/selectDetail", {
                id: fruitId
            }, function (resp) {
                let fruit = resp.data;

                if (fruit) {
                    $("#fruit_name").html(fruit.name + "属性点");
                    $("#fruit_image").attr("src", fruit.image);
                    $("#property_name").html(fruit.name);
                }
            }, error);

            $("#fruilt_detail").dialog("open");
        }
    }
}

/**
 * 将数字格式化为通过指定分隔符分割的字符串
 * @param number 待分割的数字
 * @return String
 */
function format(number) {
    if (number < 0) {
        throw new Error("不支持负数的格式化！");
    } else if (number<= 999) { // 不超过3位数，直接返回
        return number;
    } else {
        let interval = 3;
        let delimiter = ",";

        // 将其转为字符串
        let data = number + "";

        // 得到数字的位数
        let length = data.length;

        let str = "";
        let start = 0;
        let count = length / 3;
        let modCount = length % 3;

        if (modCount > 0) {
            str += data.substring(0, modCount);
            str += delimiter;

            start += modCount;
        }

        for (let i = 1; i <= count; i ++) {
            str += data.substring(start, start + interval);

            start += interval;

            str += delimiter;
        }

        return str.substring(0, str.length- 1);
    }
}

$(function () {

    $("#role_id").combobox({
        url: "/role_account/selectAll",
        valueField: "id",
        textField: "name",
        width: 160,
        prompt: "-选择角色-",
        panelHeight: "auto",
        formatter: function(row) {
            ajaxGet("/role_category/selectById", {
                id: row.categoryId
            }, function(resp) {
                let data = resp.data;

                $("#modeling_" + row.id).attr("src", data.image);
            }, error);

            return "<img height='18' id='modeling_" + row.id + "' />&nbsp;" + row.name;
        }
    });

    $("#search").linkbutton({
        iconCls: "icon-search"
    }).click(function() {
        let roleId = $("#role_id").combobox("getValue");

        $("#potency_list").datagrid("reload", {
            roleId: roleId
        });
    });

    $("#clear").linkbutton({
        iconCls: "icon-delete"
    }).click(function() {
        $("#search_form").form("clear");
    });

    /******************************************************************************************************/

    $("#propertyId").combobox({
        url: "/property/selectByType?type=2",
        valueField: "id",
        textField: "name",
        width: 150,
        required: true,
        panelHeight: "auto"
    });

    $("#location").numberspinner({
        min: 1,
        max: 79,
        width: 150,
        required: true
    });

    $("#roleId").combobox({
        url: "/role_account/selectAll",
        valueField: "id",
        textField: "name",
        width: 150,
        required: true,
        panelHeight: "auto",
        formatter: function(row) {
            ajaxGet("/role_category/selectById", {
                id: row.categoryId
            }, function(resp) {
                let data = resp.data;

                $("#role_" + row.id).attr("src", data.image);
            }, error);

            return "<img height='20' id='role_" + row.id + "' />&nbsp;" + row.name;
        }
    });

    $("#potency_dialog").dialog({
        title: "潜能果信息",
        width: 440,
        buttons: [{
            iconCls: "icon-save",
            text: "保存",
            handler: function() {
                let selector = "#potency_form";

                checkForm(selector, function () {
                    let data = $(selector).serialize();

                    ajaxPost(requestUrl, data, function(resp) {
                        showMsg(resp.message);

                        $(selector).form("clear");
                        $("#potency_dialog").dialog("close");
                        $("#potency_list").datagrid("reload");
                    }, error);
                });
            }
        }, {
            iconCls: "icon-cancel",
            text: "取消",
            handler: function() {
                $("#potency_dialog").dialog("close");
                $("#potency_form").form("clear");
            }
        }]
    });

    /******************************************************************************************************/

    $("#role_list").datalist({
        url: "/role_account/selectAll",
        idField: "id",
        valueField: "id",
        textField: "name",
        width: 178,
        height: 476,
        textFormatter: function(value, rowData, rowIndex) {
            let html = "";

            html += "<table style='border-spacing:0;'>";
            html += 	"<tr>";
            html += 		"<td rowspan=2>";
            html += 			"<div style='width:47px;height:47px;'>";
            html += 				"<img width='45' id='role__" + rowData.id + "' />";
            html += 			"</div>";
            html += 		"</td>";

            html += 		"<td colspan=2>";
            html += 			"<span>" + rowData.name + "</span>";
            html += 		"</td>";
            html += 	"</tr>";

            html += 	"<tr>";
            html += 		"<td>";
            html += 			"<img width='20' id='school_" + rowData.id + "' />";
            html += 		"</td>";

            html += 		"<td>";
            html += 			"<span>" + rowData.grade + "级</span>";
            html += 		"</td>";
            html += 	"</tr>";
            html += "</table>";

            ajaxGet("/role_category/selectById", {
                id: rowData.categoryId
            }, function(resp) {
                let data = resp.data;

                $("#role__" + rowData.id).attr("src", data.image)
                    .attr("title", data.name);
            }, error);

            ajaxGet("/school/selectById", {
                id: rowData.schoolId
            }, function(resp) {
                let data = resp.data;

                $("#school_" + rowData.id).attr("src", data.image)
                    .attr("title", data.name);
            }, error);

            return html;
        },
        onSelect: function(rowIndex, rowData) {
            if(rowData) {
                let roleId = rowData.id;

                $("#potency_schema").combobox("reload", {
                    roleId: roleId
                });

                // 使用定时任务防止combobox数据未加载完成的问题
                setTimeout(function () {
                    // 获取combobox数据
                    let list = $("#potency_schema").combobox("getData");

                    for (let i = 0; i < list.length; i++) {
                        let potency_schema = list[i];

                        // 选中开启的潜能果方案
                        if (potency_schema.openStatus === 1) {
                            $("#potency_schema").combobox("setValue", potency_schema.id);

                            break;
                        }
                    }
                }, 500);
            }
        }
    });

    $("#potency_schema").combobox({
        url: "/potency_fruit_schema/selectByRoleId",
        valueField: "id",
        textField: "name",
        width: 186,
        editable: false,
        onSelect: function (record) {
            if (record) {
                let roleId = record.roleId;
                let schemaId = record.id;

                fetchFruilt();

                // 查询角色的潜能果
                ajaxGet("/potency_fruit/selectList", {
                    roleId: roleId,
                    schemaId: schemaId
                }, function (resp) {
                    let list = resp.data;

                    if (list && list.length > 0) {
                        loadFruilt();

                        // 查询潜能果加成属性
                        ajaxGet("/potency_fruit/selectAdditiveProperties", {
                            roleId: roleId
                        }, function (resp) {
                            let list = resp.data;
                            let content = "";

                            if (list && list.length > 0) {
                                for (let i = 0; i < list.length; i++) {
                                    let data = list[i];

                                    content += "<div style='margin: 10px;'>";
                                    content += "<span style='font-size: 18px;'>" + data.name + "</span>";

                                    content += "<table>"

                                    let properties = data.list;

                                    for (let j = 0; j < properties.length; j++) {
                                        let property = properties[j];

                                        content += "<tr>";
                                        content += "<td>" + property.propertyName + "</td>";
                                        content += "<td class='green'>+" + property.propertyValue + "</td>";
                                        content += "</tr>";
                                    }

                                    content += "</table>"
                                    content += "</div>";
                                }
                            }

                            $("#additive_properties").empty().append(content);
                        }, error);

                        // 查询潜能果图案详情列表
                        ajaxGet("/potency_fruit_pattern_type/selectDetails", {
                            roleId: roleId,
                            schemaId: schemaId
                        }, function (resp) {
                            let list = resp.data;
                            let content = "";

                            if (list && list.length > 0) {
                                for (let i = 0; i < list.length; i++) {
                                    let data = list[i];

                                    content += "<div class='potency_patterns'>";
                                    content += "<span style='font-size: 18px;'>" + data.name + "</span>";
                                    content += "<span class='count'>" + data.count + "</span>";
                                    content += "<span style='float:right;margin-right: 10px;'>";
                                    content += "<a href='javascript:void(0)' onclick='loadPattern(" + data.id + ")'>&gt;</a>";
                                    content += "</span>";
                                    content += "</div>";
                                }
                            }

                            $("#potency_patterns").empty().append(content);
                        }, error);

                        // 查询兑换下一个潜能果的经验
                        ajaxGet("/potency_fruit/selectExchangeExp", {
                            roleId: roleId
                        }, function (resp) {
                            let exchageExp = resp.data;

                            $("#current_exp").progressbar("setText", "{value}/" + exchageExp);

                            // 查询角色经验
                            ajaxGet("/role_exp/selectByRoleId", {
                                roleId: roleId
                            }, function (resp) {
                                let data = resp.data;

                                if (data) {
                                    let currentExp = data.exp;

                                    $("#current_exp").progressbar("setValue", currentExp)
                                        .progressbar("setPercent", currentExp * 100 / exchageExp);
                                }
                            }, error);
                        }, error);
                    }
                }, error);
            }
        }
    });

    $("#tabs").tabs({
        fit: true,
        pill: true,
        border: true,
        narrow: false,
        closable: false,
        justified: true,
        showHeader: true,
        tabPosition: "bottom"
    });

    $("#additive_properties").panel({
        fit: true
    });

    $("#potency_pattrens").panel({
        fit: true
    });

    $("#potency_fruit").panel({
        fit: true
    });

    $("#current_exp").progressbar({
        width: 380
    }).progressbar("setColor", "#32CD32");

    $("#exchange").linkbutton({
        text: "&emsp;&emsp;兑&ensp;换&emsp;&emsp;",
        onClick: function () {
            let rowData = $("#role_list").datalist("getSelected");

            if (rowData) {
                let roleId = rowData.id;

                ajaxPost("/potency_fruit/exchange", {
                    roleId: roleId
                }, function (resp) {
                    showMsg(resp.message);

                    $("#role_list").datalist("selectRecord", roleId);
                }, error);
            }
        }
    });

    $("#detail_dialog").dialog({
        title: "潜能果"
    });

    /******************************************************************************************************/

    $("#fruilt_detail > div > .splitter").textbox({
        width: 180
    });

    $("#more").menubutton({
        menu: "#more-menu"
    });

    /**
     * 更换属性
     */
    $("#change").on("click", function () {
        // 查询角色潜能果详情
        if (fruitId != null) {
            ajaxGet("/potency_fruit/selectDetail", {
                id: fruitId
            }, function (resp) {
                let fruit = resp.data;

                if (fruit) {
                    $("#property_image").attr("src", fruit.image);
                    $("#fruilt_property").html(fruit.name);
                }
            }, error);

            $("#change_dialog").dialog("open");
        }
    });

    /**
     * 返还经验
     */
    $("#return").on("click", function () {
        // 查询角色潜能果详情
        if (fruitId != null) {
            ajaxGet("/potency_fruit/selectDetail", {
                id: fruitId
            }, function (resp) {
                let fruit = resp.data;

                if (fruit) {
                    $("#return_property_image").attr("src", fruit.image);
                    $("#return_property").html(fruit.name);
                    $("#target_count").html(toalCount - 1);
                    $("#orign_count").html(toalCount);

                    let a1 = 3000;
                    let d = 1000;
                    let an = a1 + (toalCount - 1) * d;

                    $("#return_exp").html(format(an * 10000));
                    $("#need_silver").html(format(an * 100));
                }
            }, error);

            $("#return_dialog").dialog("open");
        }
    });

    /**
     * 移动位置
     */
    $("#move").linkbutton({
        text: "&ensp;移动位置&ensp;",
        onClick: function () {
            if (fruitId != null) {
                moveMode = true; // 开启移动模式
                orignId = fruitId; // 设置orignId

                $("#fruilt_detail").dialog("close");
            } else {
                alertMsg("请先点击要移动的潜能果！");
            }
        }
    });

    $("#fruilt_detail").dialog({
        width: 210,
        title: " "
    });

    /******************************************************************************************************/

    $("#target_property").combobox({
        url: "/property/selectByType?type=2",
        valueField: "id",
        textField: "name",
        width: 120,
        panelHeight: "auto",
        formatter: function (record) {
            return "<img height='20' src='" + record.image + "'/>" + record.name;
        }
    })

    $("#change_dialog > .splitter").textbox({
        width: 280
    });

    $("#cancel").linkbutton({
        text: "&emsp;取&ensp;消&emsp;",
        onClick: function () {
            $("#change_dialog").dialog("close");
        }
    });

    $("#renewal").linkbutton({
        text: "&emsp;更&ensp;换&emsp;",
        onClick: function () {
            let propertyId = $("#target_property").combobox("getValue");

            if (propertyId) {
                ajaxPost("/potency_fruit/renewal", {
                    fruitId: fruitId,
                    propertyId: propertyId
                }, function () {
                    let roleId = $("#role_list").datalist("getSelected");

                    $("#role_list").datalist("selectRecord", roleId);

                    $("#change_dialog").dialog("close");
                    $("#fruilt_detail").dialog("close");
                }, error);
            }
        }
    });

    $("#change_dialog").dialog({
        width: 280,
        title: "更换潜能果属性"
    });

    /******************************************************************************************************/

    $("#help").linkbutton({
        iconCls: "icon-help",
        onClick: function () {
            $("#return_dialog").dialog("close");
        }
    });

    $("#return_cancel").linkbutton({
        text: "&emsp;取&ensp;消&emsp;",
        onClick: function () {
            $("#return_dialog").dialog("close");
        }
    });

    $("#return_confirm").linkbutton({
        text: "&emsp;确认返还&emsp;",
        onClick: function () {
            ajaxPost("/potency_fruit/return", {
                fruitId: fruitId
            }, function () {
                let roleId = $("#role_list").datalist("getSelected");

                $("#role_list").datalist("selectRecord", roleId);

                $("#return_dialog").dialog("close");
                $("#fruilt_detail").dialog("close");
            }, error);
        }
    });

    $("#return_dialog").dialog({
        width: 280,
        title: "经验返还"
    });

    /******************************************************************************************************/

    /**
     * 表格体的高度
     * @type {number}
     */
    let height_body = heigt_tr_with_role_details * 10;
    /**
     * 表格高度
     * @type {number}
     */
    let height_table = heigt_tool + heigt_header + height_body + heigt_footer + heigt_scoll_bar + 2;

    $("#potency_list").datagrid({
        url: "/potency_fruit/selectByPage",
        method: "get",
        height: height_table,
        rownumbers: true,
        pagination: true,
        fitColumns: true,
        toolbar: [{
            iconCls: "icon-add",
            text: "添加",
            handler: function() {
                addHandler();
            }
        }, "-", {
            iconCls: "icon-edit",
            text: "修改",
            handler: function() {
                editHandler();
            }
        }, "-", {
            iconCls: "icon-delete",
            text: "删除",
            handler: function() {
                deleteHandler();
            }
        }, "-", {
            iconCls: "icon-search",
            text: "查看",
            handler: function() {
                viewHandler();
            }
        }],
        columns: [[
            {field: "id", hidden: true},
            {field: "propertyId", title: "属性", align: "center", width: 150
                , formatter: function(value, rowData, rowIndex) {
                    if (value) {
                        ajaxGet("/property/selectById", {
                            id: value
                        }, function (resp) {
                            let data = resp.data;

                            $("#propperty_" + rowIndex).html(data.name);
                        }, error);

                        return "<span class='blue' id='propperty_" + rowIndex + "'></span>";
                    }
                }
            },
            {field: "location", title: "位置", align: "center", width: 160},
            roleDetailsColumn
        ]]
    });

});